package utils;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;
import net.sourceforge.javaocr.ocrPlugins.mseOCR.*;
import net.sourceforge.javaocr.scanner.PixelImage;

@SuppressWarnings("deprecation")
public class OCRUtils implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3898779080396729874L;
	/**
	 * 
	 */
	private Image image;
	private OCRScanner scanner;
	public OCRUtils() {
		scanner = new OCRScanner();
	}

	public void loadTrainingImages(List<URL> trainingImages) {
		String trainingImageDir = "./OCRTrainingImages";
		if (!trainingImageDir.endsWith(File.separator)) {
			trainingImageDir += File.separator;
		}
		try {
			scanner.clearTrainingImages();
			TrainingImageLoader loader = new TrainingImageLoader();
			HashMap<Character, ArrayList<TrainingImage>> trainingImageMap = new HashMap<Character, ArrayList<TrainingImage>>();
			for (URL url : trainingImages) {
				
				image = ImageIO.read(url);
				if (url.getFile().contains("ascii.png")){
					loader.load(image, new CharacterRange('!', '~'), trainingImageMap,"ascii.png");
				}else if (url.getFile().contains("hpljPica.jpg")){
					loader.load(image, new CharacterRange('!', '~'), trainingImageMap,"hpljPica.jpg");
				}else if (url.getFile().contains("digits.jpg")){
					loader.load(image, new CharacterRange('0', '9'), trainingImageMap,"digits.jpg");
				}
				
				
			}
			scanner.addTrainingImages(trainingImageMap);
		}catch (IOException e) {
			System.exit(-1);
		}
		
		
	}

	public String process(URL imageURL) {
		try {
			image = ImageIO.read(imageURL);
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (image == null) {
			System.err.println("Cannot find image file: " + imageURL);
			return "";
		}
		PixelImage pixelImage = new PixelImage(image);
		pixelImage.toGrayScale(true);
		pixelImage.filter();
		String text = scanner.scan(image, 0, 0, 0, 0, null);
		return text;
	}
	public static void main(String[] args) throws MalformedURLException {
		OCRUtils demo = new OCRUtils();
//		demo.loadTrainingImages();
		System.out.println("done loading images");
		URL imageURL = new URL("http://www.columbiamt.com/CMT-Marking-Stamps/images/OCR-A-Font.gif");
		System.out.println("result = " + demo.process(imageURL));
	}
	
	
}
